<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04-文字</title>
  <style>
    body {
      background-color: #000;
      text-align: center;
    }
    #c1 {
      background-color: #fff;
    }
  </style>
</head>
<body>
  <canvas id="c1" width="800" height="600"></canvas>

  <script>
    window.onload = function() {
      const oC = document.getElementById('c1')
      const gd = oC.getContext('2d')

      const startX = 400
      const startY = 300
      // 文字行高
      const lineHeight = 16
      // const str = 'hello world'
      const str = 'jlgzf'
      // const str = '涨幅'

      gd.beginPath()
      // font样式设置与css相同
      // gd.font = lineHeight + 'px serif'
      // gd.font = lineHeight + 'px sans-serif'
      gd.font = lineHeight + 'px Arial'
      // gd.font = lineHeight + 'px SimHei'
      // gd.font = lineHeight + 'px Microsoft Yahei'

      const text = gd.measureText(str)
      // 文字实际的边界：上、下、左、右。以及宽度
      console.log(text.actualBoundingBoxAscent)
      console.log(text.actualBoundingBoxDescent)
      console.log(text.actualBoundingBoxLeft)
      console.log(text.actualBoundingBoxRight)
      console.log(text.width)
      
      // 上边框: actualBoundingBoxAscent 下边框: actualBoundingBoxDescent。这里上下边框显示基于文字的基线
      // const margin = 0
      // 上边框与顶部距离。下边框与顶部距离。通过大量实验得出系数 7 比较符合计算出来的实际效果
      const margin = Math.ceil((text.actualBoundingBoxAscent + text.actualBoundingBoxDescent) / 7)

      // 文字填充颜色
      gd.fillStyle = 'red'
      gd.fillText(str, startX, startY)

      // 上
      gd.beginPath()
      gd.moveTo(startX + text.actualBoundingBoxLeft, startY - text.actualBoundingBoxAscent)
      gd.lineTo(startX + text.actualBoundingBoxRight, startY - text.actualBoundingBoxAscent)
      gd.stroke()

      // 下
      gd.beginPath()
      gd.moveTo(startX + text.actualBoundingBoxLeft, startY + text.actualBoundingBoxDescent)
      gd.lineTo(startX + text.actualBoundingBoxRight, startY + text.actualBoundingBoxDescent)
      gd.stroke()

      // 左
      gd.beginPath()
      gd.moveTo(startX + text.actualBoundingBoxLeft, startY - text.actualBoundingBoxAscent)
      gd.lineTo(startX + text.actualBoundingBoxLeft, startY + text.actualBoundingBoxDescent)
      gd.stroke()

      // 右
      gd.beginPath()
      gd.moveTo(startX + text.actualBoundingBoxRight, startY - text.actualBoundingBoxAscent)
      gd.lineTo(startX + text.actualBoundingBoxRight, startY + text.actualBoundingBoxDescent)
      gd.stroke()
    }
  </script>
</body>
</html>